<?php
namespace Dft\Controllers;

use Silex\Application;
use Silex\ControllerProviderInterface;
use Silex\ControllerCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Secret\Common\Utils;

class PageCSP implements ControllerProviderInterface {

	public function connect(Application $app) {
		$content = array();
		$controllers = $app['controllers_factory'];
		$controllers->match('/', array($this,'first'), 'GET');
		$controllers->match('/{lang}/', array($this,'page'), 'GET');
		$controllers->match('/{lang}/{urlFragment}/', array($this,'page'), 'GET');
		return $controllers;
	}

	public function first(Application $app, Request $request) {
		$repo = $app['em']->getRepository('Secret\Entities\Content');
		$pages = $repo->data('Page', '', array(), array('sort' => 'rank', 'order' => 'ASC'));
		$nav = Utils::buildTree(array('id' => 0), $pages['_data']);
		return $app['twig']->render("html5up-aerial/index.twig", array(
			'nav' => $nav
		));
	}
	
	public function page(Application $app, Request $request, $lang = null, $urlFragment = '') {
		global $CMS_COLUMN_META;
		$repo = $app['em']->getRepository('Secret\Entities\Content');
		$model = $repo->model('Page');
		if (!$lang) {
			$app->abort(404);
		}
		$result = $repo->data($model, 'entity.urlFragment = :v1', array('v1' => urldecode($urlFragment)), array('sort' => 'rank','order' => 'ASC'));
		if (count($result['_data']) == 0) {
			$result = $repo->data($model, 'entity.slug = :v1', array('v1' => urldecode($urlFragment)), array('sort' => 'rank','order' => 'ASC'));
		}
		if (count($result['_data']) == 0) {
			$result = $repo->data($model, 'entity.title = :v1', array('v1' => urldecode($urlFragment)), array('sort' => 'rank','order' => 'ASC'));
		}
		if (count($result['_data']) == 0) {
			$result = $repo->data($model, 'entity.id = :v1', array('v1' => urldecode($urlFragment)), array('sort' => 'rank','order' => 'ASC'));
		}
		if (count($result['_data']) == 0) {
			$app->abort(404);
		}
		
		$id = $request->get('id');
		$pages = $repo->data('Page', '', array(), array('sort' => 'rank', 'order' => 'ASC'));
		$nav = Utils::buildTree(array('id' => 0), $pages['_data']);
		return $app['twig']->render($result['_data'][0]['template'], array(
			'page' =>$result['_data'][0],
			'nav' => $nav,
			'lang' => $lang,
			'urlFragment' => $urlFragment,
			'id' => $id,
		));
	}
}